<template>
  <div class="class-container">
    <div class="app-container">
      <el-card class="box-card">

        <!-- 页头 -->
        <div
          slot="header"
          class="clearfix"
        >
          <span>班级管理</span>
          <div class="form">

            <div class="add">
              <el-button
                type="primary"
                @click="addClassFn()"
              >添加班级</el-button>
            </div>
          </div>
        </div>

        <!-- 筛选 -->
        <div class="screen">
          <el-form
            :rules="queryRules"
            inline
            :model="query"
            ref="screenForm"
          >
            <el-form-item
              label="学部"
              prop="faculty"
            >
              <el-select
                filterable
                clearable
                v-model="query.faculty"
                placeholder="请选择学部"
              >
                <el-option
                  v-for="(item, index) in facultyOptions"
                  :key="index"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="年级"
              prop="grade"
            >
              <el-select
                filterable
                clearable
                v-model="query.grade"
                placeholder="请选择年级"
              >
                <el-option
                  v-for="(item, index) in gradeOptions"
                  :key="index"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="模糊查询名称">
              <el-input
                v-model.trim="query.name"
                clearable
                placeholder="请输入名称关键字"
                @keyup.enter.native="screenSubmitFn()"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="screenSubmitFn()"
              >筛选</el-button>
              <el-button @click="screenResetFn()">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 表格组件 -->
        <div
          class="table"
          style="height:80%"
        >
          <el-table
            :data="classList"
            style="width: 100%"
          >
            <el-table-column
              type="index"
              label="序号"
              min-width='100px'
            >
            </el-table-column>
            <el-table-column
              prop="name"
              label="班级"
              min-width='150px'
            >
            </el-table-column>
            <el-table-column
              prop="faculty"
              label="学部"
              min-width='150px'
            >
            </el-table-column>
            <el-table-column
              prop="grade"
              label="年级"
              min-width='120px'
            >
            </el-table-column>
            <el-table-column
              label="操作"
              width='165x'
              fixed='right'
            >
              <template v-slot="{row}">
                <el-button
                  circle
                  size="mini"
                  icon="el-icon-search"
                  @click="rowInfoFn(row)"
                ></el-button>
                <el-button
                  type="primary"
                  circle
                  icon="el-icon-edit"
                  size="mini"
                  @click="rowUpdateFn(row)"
                ></el-button>

                <el-popconfirm
                  title="确定删除该班级吗？执行此操作将同时删除属于该班级的学生！"
                  @confirm="rowDeleteFn(row)"
                >
                  <el-button
                    slot="reference"
                    type="danger"
                    circle
                    icon="el-icon-delete"
                    size="mini"
                  ></el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px; margin-top: 40px;"
          v-if="total > query.pagesize"
        >
          <!-- 分页区域 -->
          <el-pagination
            :current-page="query.page"
            :page-sizes="[10, 15, 20, 25]"
            :page-size="query.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            hide-on-single-page
          />
        </el-row>

        <el-dialog
          title="班级信息"
          :visible.sync="dialogInfoVisible"
          @close="dialogCloseFn()"
          :show-close='false'
          custom-class='dialog-info-35'
        >
          <el-descriptions
            border
            :column='1'
            labelClassName="width-100"
          >
            <el-descriptions-item label="id号">{{classInfo.id}}</el-descriptions-item>
            <el-descriptions-item label="班级">{{classInfo.name}}</el-descriptions-item>
            <el-descriptions-item label="学部">{{classInfo.faculty}}</el-descriptions-item>
            <el-descriptions-item label="年级">{{classInfo.grade}}</el-descriptions-item>
          </el-descriptions>
        </el-dialog>

        <el-dialog
          :title="isAdd ? '添加班级':'修改班级信息'"
          :visible.sync="dialogUpdateVisible"
          @close="dialogCloseFn()"
          :close-on-click-modal='false'
          :show-close='false'
          custom-class='dialog-30'
        >
          <el-form
            :model="classInfo"
            status-icon
            :rules="classRules"
            ref="classInfo"
            label-width="80px"
          >
            <el-form-item
              label="班级名称"
              prop="name"
            >
              <el-input
                v-model.trim="classInfo.name"
                @keyup.enter.native="updateSubmitFn()"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="年级"
              prop="grade"
            >
              <el-select
                filterable
                clearable
                v-model="classInfo.grade"
                placeholder="请选择年级"
              >
                <el-option
                  v-for="(item, index) in gradeOptions"
                  :key="index"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="学部"
              prop="faculty"
            >
              <el-select
                filterable
                clearable
                v-model="classInfo.faculty"
                placeholder="请选择学部"
              >
                <el-option
                  v-for="(item, index) in facultyOptions"
                  :key="index"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="center">
              <el-button @click="dialogUpdateVisible = false">取消</el-button>
              <el-button
                type="primary"
                @click="updateSubmitFn()"
              >{{isAdd ? '添加':'修改'}}</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>

      </el-card>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  getClassListAPI,
  updateClassAPI,
  deleteClassAPI,
  addClassAPI,
  getFacultyListAPI,
  getGradeListAPI
} from '@/api'
export default {
  name: 'classList',
  computed: {
    ...mapGetters(['userInfo'])
  },
  data () {
    // 判断是有对应的学部
    const validFaculty = (rule, value, callback) => {
      value &&
        (this.facultyOptions.includes(value)
          ? callback()
          : callback(new Error('学部不存在')))
      callback()
    }
    // 判断是有对应的年级
    const validGrade = (rule, value, callback) => {
      value &&
        (this.gradeOptions.includes(value)
          ? callback()
          : callback(new Error('年级不存在')))
      callback()
    }
    return {
      query: {
        page: 1, // 页码
        pagesize: 10, // 每页条数
        name: '',
        faculty: '',
        grade: ''
      }, // 获取列表数据
      classList: [], // 班级信息列表
      total: 0, // 总数
      queryRules: {
        name: [
          {
            min: 1,
            max: 10,
            type: 'string',
            message: '班级名称要求1-10个数字',
            trigger: 'blur'
          }
        ],
        faculty: [{ validator: validFaculty, trigger: 'blur' }],
        grade: [{ validator: validGrade, trigger: 'blur' }]
      }, // 查找数据验证
      dialogInfoVisible: false, // 信息展示 dialog 控制
      dialogUpdateVisible: false, // 修改信息 dialog 控制
      classInfo: {}, // dialog 数据
      classRules: {
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 10,
            type: 'string',
            message: '班级名称要求1-10个数字',
            trigger: 'blur'
          }
        ],
        faculty: [
          {
            required: true,
            message: '学部不能为空',
            trigger: 'change'
          },
          { validator: validFaculty, trigger: 'blur' }
        ],
        grade: [
          {
            required: true,
            message: '年级不能为空',
            trigger: 'change'
          },
          { validator: validGrade, trigger: 'blur' }
        ]
      }, // dialog 数据验证
      isAdd: false, // 是否是添加操作
      facultyOptions: [], // 筛选学部数据
      gradeOptions: [] // 筛选年级数据
    }
  },
  created () {
    this.getClassListFn()
    this.getFacultyTypeFn()
    this.getGradeFn()
  },
  methods: {
    // 每页显示的条数发生改变时触发
    handleSizeChange (newSize) {
      this.query.size = newSize
      this.getClassListFn() // 获取班级列表
    },
    // 当前页面发生改变时触发
    handleCurrentChange (newPage) {
      this.query.page = newPage
      this.getClassListFn() // 获取班级列表
    },
    // 获取班级列表 -> 发送请求
    async getClassListFn () {
      try {
        const { success, code, data } = await getClassListAPI(this.query)
        if (success && code === 10000) {
          this.classList = data.row
          this.total = data.total
        }
      } catch (err) {
        return console.dir(err)
      }
    },
    // 获取学部 -> 发送请求
    async getFacultyTypeFn () {
      try {
        const { success, code, data } = await getFacultyListAPI({
          page: 1
        })
        if (success && code === 10000) {
          data.row.forEach((item) => {
            this.facultyOptions.push(item.name)
          })
        }
      } catch (err) {
        return console.dir(err)
      }
    },
    // 获取年级 -> 发送请求
    async getGradeFn () {
      try {
        const { success, code, data } = await getGradeListAPI({
          page: 1
        })
        if (success && code === 10000) {
          data.row.forEach((item) => {
            this.gradeOptions.push(item.name)
          })
        }
      } catch (err) {
        return console.dir(err)
      }
    },
    // 点击查看 -> 展示数据详情
    rowInfoFn (row) {
      this.classInfo = row
      this.dialogInfoVisible = true
    },
    // 点击修改 -> 展示数据 -> 修改
    rowUpdateFn (row) {
      this.classInfo = { ...row }
      this.isAdd = false
      this.dialogUpdateVisible = true
    },
    // 点击删除 -> 删除该班级
    async rowDeleteFn (row) {
      try {
        const { success, code } = await deleteClassAPI(row.id)
        if (success && code === 10000) {
          success && this.getClassListFn()
        }
      } catch (err) {
        return console.dir(err)
      }
    },
    // dialog 关闭
    dialogCloseFn () {
      this.classInfo = this.$options.data().classInfo
      this.$refs.classInfo?.resetFields()
    },
    // dialog 点击添加/修改 -> 发起请求
    async updateSubmitFn () {
      this.$refs.classInfo.validate(async (valid) => {
        if (valid) {
          try {
            delete this.classInfo.state
            let success, code
            if (this.isAdd) {
              ; ({ success, code } = await addClassAPI(this.classInfo))
            } else {
              ; ({ success, code } = await updateClassAPI(this.classInfo))
            }

            if (success && code === 10000) {
              this.query.name = ''
              this.getClassListFn()
              this.dialogUpdateVisible = false
            }
          } catch (err) {
            return console.dir(err)
          }
        }
      })
    },
    // 点击添加按钮
    addClassFn () {
      this.isAdd = true
      this.dialogUpdateVisible = true
    },
    // 点击筛选按钮 -> 重新获取列表
    screenSubmitFn () {
      this.$refs.screenForm.validate(async (valid) => {
        valid && this.getClassListFn()
      })
    },
    // 清空筛选数据 -> 重新获取列表
    screenResetFn () {
      this.query = this.$options.data().query
      this.$refs.screenForm?.resetFields()
      this.getClassListFn()
    }
  }
}
</script>

<style lang="less" scoped>
.clearfix {
  display: flex;
}
.form {
  text-align: right;
  flex-grow: 1;
}
.title {
  flex-grow: 0;
}
.form {
  display: flex;
  justify-content: right;
}
.screen {
  display: flex;
}
</style>
